﻿using IM.Easy.Entity.Scheduled;
using IM.Easy.ScheduledServices.Dtos;
using IM.Easy.ScheduledServices.IServices;
using Quartz;

namespace IM.Easy.Api.HostedService
{
    public class QuartzInitializationService : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;
        private ScheduledLogger scheduledLogger { get; set; }


        public QuartzInitializationService(
            IServiceProvider serviceProvider,
            ScheduledLogger scheduledLogger)
        {
            _serviceProvider = serviceProvider;
            this.scheduledLogger = scheduledLogger;
        }


        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using var scope = _serviceProvider.CreateScope();
            var scheduledJobService = scope.ServiceProvider.GetRequiredService<IScheduledJobService>();
            var scheduler = scope.ServiceProvider.GetRequiredService<ISchedulerService>();
            var jobs = scheduledJobService.GetScheduleds();


            var tasks = jobs.Select(job => scheduler.NewScheduler(job));
            await Task.WhenAll(tasks);

            scheduler.Scheduler.ListenerManager.AddTriggerListener(scheduledLogger);

            await scheduler.Scheduler.Start(cancellationToken);
            Console.WriteLine("任务调度器初始化完成");
        }


        public async Task StopAsync(CancellationToken cancellationToken)
        {
            using var scope = _serviceProvider.CreateScope();
            var scheduler = scope.ServiceProvider.GetRequiredService<ISchedulerService>();
            await scheduler.Scheduler.Shutdown(cancellationToken);
        }
    }
}
